package com.flower.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.flower.pojo.User;


/*
 * 登录拦截器
 * */
public class LoginInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		//获取请求的URL
		String uri = request.getRequestURI();//拿到上一个页面地址
		//URL:除了登录请求外，其他的URL都进行拦截控制
		if(uri.indexOf("/login.do") >= 0){
			return true;
		}
		
		//获取Session
		User user = (User) request.getSession().getAttribute("USER");
		//判断Session中是否有用户数据，如果有，则返回true，继续向下执行
		if(user != null){
			return true;
		}
		
		//不符合条件的给出提示信息，并转发到登录页面
		request.setAttribute("msg", "您还没有登录，请先登录");
		request.getRequestDispatcher("/login.jsp").forward(request, response);;
		
		return false;
	}
	
	// 在处理过程中，执行拦截
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
	}

	// 执行完毕，返回前拦截
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2, ModelAndView arg3) throws Exception {
	}

}
